/**
 * 
 */

//ipPort = '10.58.88.212:8080';

var __auto_parse = Ext.util.Cookies.get('__auto_parse')=='true';

Ext.define('Case.Detail', {
	extend: 'Ext.panel.Panel',
	alias: 'case.detail',
	
	initComponent: function(){
		me_detail = this;
		waitingSubCases = new Array;
		caseIdForSubCase = new Array;

		subCaseNames = new Array;
		profileStore = Ext.create('Ext.data.Store', {
			model: 'Profile'
		});
		Ext.apply(me_detail, {
            region: 'center',
            layout: 'border',
            border: false,
            disabled: true,
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: [{
                    text: 'New',
                    menu: [{
                    	text: 'Step',
                    	handler: function() {
                            Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
                                    if (btn=='ok'){
                                    	++overallSteps;
                                    	//alert(overallSteps);
                                    	//alert(text + " " + overallSteps);
                                        me_detail.steps.add(Ext.create('case.step', {
                                            title: text,
                                            id: text + String(overallSteps)
                                        }));
                                        	
                                    }
                            });
            			}
                    }, {
                    	text: 'SubCase',
                    	handler: function() {
                            Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
                                    if (btn=='ok'){
                                    	++overallSubcases;
                                        me_detail.subcases.add(Ext.create('case.sub',{title:text, id:text + String(overallSubcases)}));
                                    }
                            });            				
            			}
                    }]
                }, {
                	text: 'Save',
                	handler: function() {
                		//steps
                		//todo: the dirty data is stored in "data" property, need to check if it's sent to server
                		me_detail.model.data.profilegroupId = me_detail.dockedItems.items[0].items.items[4].getValue();
                		me_detail.model.data.steps = [];
                		me_detail.steps.items.each(function(stepPanel) {
                			var stepModel = stepPanel.getStepModel();
                			me_detail.model.data.steps.push(stepModel.data);
                		});
                		//subcases
                		me_detail.model.data.subcases = [];
                		me_detail.subcases.items.each(function(subcasePanel) {
                			var subcaseModel = subcasePanel.getSubCaseModel();
                            me_detail.model.data.subcases.push(subcaseModel.data);
                		});
//                		me_detail.model.data.name = "";
//                		me_detail.model.data.name.push();
                		me_detail.setLoading('Saving');
                		me_detail.model.save({
                			success: function(caseDetail, operation) {
                				//me.model = caseDetail;
                				//me_detail.refresh(caseDetail);
                				Ext.Msg.alert('Success', 'Case is saved');
                			//	var obj = me_detail.steps.removeAll();
                                
                			},
    						callback: function() {
    							me_detail.setLoading(false);
    						}
                		});
                	}
                }, {
                	xtype: 'splitbutton',
                	text: 'Parse',
                	handler: function() {
                		me_detail.parseParams();
					},
					menu : {
                        items: [{
                            text: 'Auto Parse',
                            checked: __auto_parse,
                            handler: function(item, checked) {
                            	__auto_parse = item.checked;
                            	Ext.util.Cookies.set('__auto_parse', __auto_parse);
							}
                        }]
                    }
                },{
					text: 'Run Testcase',
					handler: function() {
                    	if (caseList.dockedItems.items[1].items.items[4].value == null){
                    		alert('Please select a server!');
                    		return;
                    	};
						var caseId = me_detail.model.data.id;
						var caseName = me_detail.model.data.name;
						var subCaseId;
						var subcases = new Array;
						if (!(me_detail.model.data.subcases.length)){
							subcases[0] = me_detail.model.data.subcases;
						} else {
							subcases = me_detail.model.data.subcases;
						};
						for (i = 0; i < subcases.length; i++){
							subCaseId = subcases[i].id;
							if (subCaseNames[subCaseId]){
								alert (caseName + ' is already running');
								return;
							};
							subCaseNames[subCaseId] = subcases[i].name;
//							statusScreen.addRow(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
							me_detail.runSubCase(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
						};

						}
				},{
					xtype: 'combobox',
					store: profileStore,
					id: 'profile',
					emptyText: 'Select Profile',
			        displayField: 'name',
			        valueField: 'id'						
				}]
            }],

            items: [{
                region: 'center',
                //title: 'Case Detail',
                layout: 'anchor',
//				anchor: '100% 80%',
                items: [me_detail.steps()]
            },{
                region: 'south',
				//anchor:'100% 20%',
				height: '20%',
                split: true,
                collapsible: false,
                //title: 'Sub Cases',
                layout: 'anchor',	
				items: [me_detail.subcases()]
            }]
		});
		me_detail.callParent(arguments);
		//me_detail.steps.on('beforeremove', me_detail.onRemoveStep);
	},

	runSubCase: function(caseId, subCaseId, caseName, subCaseName){
		statusScreen.addRow(caseId, subCaseId, caseName, subCaseName);
		var subCaseStatus = 'error';
		caseIdForSubCase[subCaseId] = caseId;
		var serverId = caseList.dockedItems.items[1].items.items[4].value;
		var serverProfiles = new Array;
		if (!(caseList.metaData.profiles.length))
			serverProfiles[0] = caseList.metaData.profiles;
		else
			serverProfiles = caseList.metaData.profiles;
		Ext.Ajax.request({
			url: 'http://' + ipPort + '/bpccase/' + caseId,
			method: 'GET',
			success: function(response){
				caseDataArray = new Array;
				caseData = Ext.decode(response.responseText);
				caseDataArray[caseData.id] = caseData;
				var profileGroupId = caseData.profilegroupId;
				if (profileGroupId == null){
					alert('There is no profile selected for ' + caseData.name + '!');
					var subcases = new Array;
					if (!(caseData.subcases.length)){
						subcases[0] = caseData.subcases;
					} else {
						subcases = caseData.subcases;
					};
					for (i = 0; i < subcases.length; i++){
						statusScreen.deleteRow(subcases[i].id);
						subCaseNames[subcases[i].id] = null;
					};
					return;
				}
				var serverProfileId = null;
				for (i = 0; i < serverProfiles.length; i++){
					if ((serverProfiles[i].groupId == profileGroupId) && (serverProfiles[i].serverId == serverId)){
						serverProfileId = serverProfiles[i].id;
						break;
					};
				};
				Ext.Ajax.request({
					url: 'http://' + ipPort + '/bpctestrun/' + subCaseId + '/' + serverProfileId,
					method: 'POST',
					subCaseId: subCaseId,
					success: function(response, subCaseId){
						var obj = Ext.decode(response.responseText);
						if (!(obj.Result[0])){
							var subCaseId = response.request.options.subCaseId;
							alert('Error in subcase with id ' + subCaseId + ' (please check in fiddler - response contains no data)');
//							statusScreen.deletRow(subCaseId);
							statusScreen.updateRow(subCaseId, 'error');
//							statusScreen.details.disable();
							subCaseNames[subCaseId] = null;
							return;
						};
						var subCaseId = obj.Result[0].subCaseId;
						waitingSubCases[subCaseId] = obj;
						var testCaseId = caseIdForSubCase[subCaseId];
						Ext.Ajax.request({
							url: 'http://' + ipPort + '/bpccase/' + testCaseId,
							method: 'GET',
							success: function(response){
								var testCaseData = Ext.decode(response.responseText);
								var tCaseId = testCaseData.id;
								var subcases  = new Array;
								if (!(testCaseData.subcases.length)){
									subcases[0] = testCaseData.subcases;
								} else {
									subcases = testCaseData.subcases;
								};
								for (i = 0; i < subcases.length; i++){
								var subCaseId = subcases[i].id;
								if (waitingSubCases[subCaseId]){
									var subCaseResult = waitingSubCases[subCaseId];
									waitingSubCases[subCaseId] = null;
									var subCaseData = subcases[i];
									var numberOfSteps = subCaseResult.Result.length;
									for (j = 0; j < numberOfSteps; j++){
										/*
										var response = subCaseResult.Result[j].response;
										if (numberOfSteps == 1){
											var expResponse = testCaseData.steps.response;
										} else {
											var expResponse = testCaseData.steps[j].response;
										};
										var expResponse = stepResult.response;
										if (subCaseData.params){
											var params = new Array;
											if (!(subCaseData.params.length)){
												params[0] = subCaseData.params;
											} else {
												params = subCaseData.params;
											};
											for (k = 0; k < params.length; k++){
												var param = params[k];
												var expResponseArray = new Array;
												var splitter = '<%' + param.name + '%>';
												expResponseArray = expResponse.split(splitter);
												expResponse = expResponseArray.join(param.value);
											};

										};	
										if (expResponse == response){
										*/
										if (subCaseResult.Result[j].result == RESULT_OK) {
											subCaseStatus = 'ok';
										} else {
											subCaseStatus = 'fail';
											break;
										};
										
									};
									statusScreen.updateRow(subCaseId, subCaseStatus);
									subCaseNames[subCaseId] = null;
								};
							};

							},
							failure: function(){
								
							},
							callback: function(){
								
							}
						});
					},
					failure: function() {
//						subCaseStatus = 'error';
					},
					callback: function() {
//						statusScreen.updateRow(subCaseId, subCaseStatus);
//						subCaseNames[subCaseId] = null;
					}
				});
			}
		});
	},
	
	steps: function(){
		this.steps = Ext.create('Ext.tab.Panel', {
			id: '__steps__',
		    bodyStyle:'padding:5px 5px 0',
		    anchor: '100% 100%',	
			activeTab: 0,
			layout: 'anchor',
			plugins: Ext.create('Ext.ux.TabCloseMenu', {
		        extraItemsTail: [
		            '-',
		            {
		                text: 'Deletable',
		                checked: true,
		                hideOnClick: true,
		                handler: function (item) {
		                    currentItem.tab.setClosable(item.checked);
		                    currentItem.tab.title = 'abcdefg';
		                }
		            },
		            {
		                text: 'Rename',
		                //checked: true,
		                hideOnClick: true,
		                handler: function (item) {
                            var itemChanging = currentItem;
                            Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
                                if (btn=='ok'){
		                            itemChanging.setTitle(text);
                                }
                            });
		                    //currentItem.doLayout();
		                }
		            }
		        ],
		        listeners: {
		            aftermenu: function () {
		                currentItem = null;
		            },
		            beforemenu: function (menu, item) {
		                var menuitem = menu.child('*[text="Deletable"]');
		                currentItem = item;
		                menuitem.setChecked(item.closable);
		            }
		        }
		    })	
		});
		return this.steps;
	},
	
	subcases: function(){
		this.subcases = Ext.create('Ext.tab.Panel',{
			activeTab: 0,
			id: '__subcases__',
			enableTabScroll: true,
			height: '100%',
			plugins: Ext.create('Ext.ux.TabCloseMenu', {
		        extraItemsTail: [
		            '-',
		            {
		                text: 'Deletable',
		                checked: true,
		                hideOnClick: true,
		                handler: function (item) {
		                    currentItem.tab.setClosable(item.checked);
		                    currentItem.tab.title = 'abcdefg';
		                }
		            },
		            {
		                text: 'Rename',
		                //checked: true,
		                hideOnClick: true,
		                handler: function (item) {
                            var itemChanging = currentItem;
                            Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
                                if (btn=='ok'){
		                            itemChanging.setTitle(text);
                                }
                            });
		                    //currentItem.doLayout();
		                }
		            },
		            {
		            	text: 'Run',
		            	hideOnClick: true,
		            	handler: function(item) {
	                    	if (caseList.dockedItems.items[1].items.items[4].value == null){
	                    		alert('Please select a server!');
	                    		return;
	                    	};
							var itemRun = currentItem;
							var subCaseId = itemRun.id.substring(7,itemRun.id.length);
							var caseId = me_detail.model.data.id;
							var caseName = me_detail.model.data.name;
							var subCaseName = itemRun.title;
							if (subCaseNames[subCaseId]){
								alert (subCaseName + ' is already running');
								return;
							}
//							statusScreen.addRow(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
							me_detail.runSubCase(caseId, subCaseId, caseName, subCaseName);
						}
		            }
		        ],
		        listeners: {
		            aftermenu: function () {
		                currentItem = null;
		            },
		            beforemenu: function (menu, item) {
		                var menuitem = menu.child('*[text="Deletable"]');
		                currentItem = item;
		                menuitem.setChecked(item.closable);
		            }
		        }
		    })	
			/*
			items:[{
				title: 'subcase2',
				html: 'I am sub case 2'
			}]*/
		});
		return this.subcases;
	},
	
	load: function(id){
		var me_detail = this;
		me_detail.setLoading('Loading', true);
		//me_detail.steps.un('beforeremove', me_detail.onRemoveStep);
		me_detail.steps.removeAll(true);
		me_detail.subcases.removeAll(true);
		
		//me_detail.steps.on('beforeremove', me_detail.onRemoveStep);
		var CaseDetail = Ext.ModelManager.getModel('CaseDetail');
		profileStore.load();
		CaseDetail.load(id, {
			success: function(detail){
				me_detail.model = detail;
				detail.steps().each(function(step){
					var stepId = step.get('id'); 
					var stepPanel = Ext.create('case.step', {
						title: step.get('name'),
						id: 'STEP' + stepId
					});
					me_detail.steps.add(stepPanel);
					stepPanel.loadRecord(step);
					/*
				    var 	formPanel = Ext.getCmp(stepId);
				    formPanel.getForm().loadRecord(step);
				    */			
				});		
				
				detail.subcases().each(function(subcase){
					var subId = subcase.get('id');
					var sub = Ext.create('case.sub', {
						title: subcase.get('name'),
						id: 'SUBCASE' + subId
					});
					sub.load(subcase);
					me_detail.subcases.add(sub);			
				});
				
				me_detail.dockedItems.items[0].items.items[4].setValue(detail.data.profilegroupId);
				me_detail.doLayout();
			},
			callback: function() {
				me_detail.setLoading(false);
			}
		});		
	},
	
	refresh: function(detail) {
		var me_detail = this;
		me_detail.model = detail;
		var i = 0;
		detail.steps().each(function(step){
			var stepPanel = me_detail.steps.items.get(i++);
			stepPanel.id = 'STEP'+step.get('id');
			stepPanel.loadRecord(step);	
		});		
		i = 0;
		detail.subcases().each(function(subcase){
			var sub = me_detail.subcases.items.get(i++);
			sub.id = 'SUBCASE' + subcase.get('id');
			sub.load(subcase);
		});		
	},
	
	onRemoveStep: function(container, panel) {
		alert("you can't remove it!!!");
		return false;
	}, 
	
	parseParams: function() {
		me_detail = this;
		//parse param in steps
		var paramNames = [];
		me_detail.steps.items.each(function(stepPanel) {
			var frm = stepPanel.getForm();
			var kvs = frm.getFieldValues();
			var req = kvs.request;
			var res = kvs.response;
			var tmpArr = me_detail.util.parse(kvs.request);
			paramNames = paramNames.concat(tmpArr);
			tmpArr = me_detail.util.parse(kvs.response);
			paramNames = paramNames.concat(tmpArr);
		});
		//update subcases
		me_detail.subcases.items.each(function(subcasePanel) {
			subcasePanel.setParamNames(paramNames);
		});
	},
	
	util: {
		parse: function(text) {
			var regex = /<%(.*?)%>/g;
			var matches;
			var paramNames = [];
			while (matches = regex.exec(text)){
				paramNames.push(matches[matches.length-1]);
			}
			return paramNames;
		}
	}
	
	 

});
